package com.caiyouxi.goods.service;

import com.caiyouxi.common.Constant;
import com.caiyouxi.common.bean.QueryParams;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.exception.ErrorCode;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.finance.model.FinanceTradeDetail;
import com.caiyouxi.finance.model.FinanceTradeReceivable;
import com.caiyouxi.finance.model.FinanceTradeReceived;
import com.caiyouxi.finance.service.*;
import com.caiyouxi.goods.mapper.GoodsCategoryMapper;
import com.caiyouxi.goods.mapper.GoodsDeliverServiceMapper;
import com.caiyouxi.goods.model.GoodsCategory;
import com.caiyouxi.goods.model.GoodsDeliverService;
import com.caiyouxi.goods.model.GoodsInfo;
import com.caiyouxi.order.model.OrderBean;
import com.caiyouxi.order.service.OrderService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/11/9.
 */
@Service
public class GoodsDeliverServiceService  extends BaseService {

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;
    @Autowired
    private GoodsDeliverServiceMapper goodsDeliverServiceMapper;
    @Autowired
    private FinanceTradeReceivableService financeTradeReceivableService;
    @Autowired
    private FinanceTradeReceivedService financeTradeReceivedService;
    @Autowired
    private FinancePaymentDetailService financePaymentDetailService;
    @Autowired
    private GoodsInfoService goodsInfoService;
    @Autowired
    private FinanceTradeDetailService financeTradeDetailService;
    @Autowired
    private FinanceAccountService financeAccountService;
    @Autowired
    private OrderService orderService;

    private Logger logger = Logger.getLogger(GoodsCategoryService.class);

    /**
     * 查询商品发货服务
     */
    public ResData get_goods_deliver_service_info(GoodsDeliverService goodsDeliverService){
        String redis_key = "GOODS_DELIVER_SERVICE"+goodsDeliverService.getId();
        logger.info("search redis...");
        GoodsDeliverService newGoodsDeliverService = (GoodsDeliverService) redisService.get(redis_key);
        if (null == newGoodsDeliverService){
            logger.info("search db...");
            newGoodsDeliverService  =goodsDeliverServiceMapper.select_goods_deliver_service(goodsDeliverService.getId());
            redisService.set(redis_key,newGoodsDeliverService);
        }
        return  success(newGoodsDeliverService);
    }

    /**
     * 查询商品发货服务列表
     */
    public ResData get_goods_deliver_service_list(GoodsDeliverService goodsDeliverService){
        Integer reids_page_size = Integer.parseInt( redisService.get("sys.pagesize").toString());
        if(null != reids_page_size){
            goodsDeliverService.setPage_size(reids_page_size);
        }
        List<GoodsDeliverService> goodsDeliverServices = goodsDeliverServiceMapper.select_goods_deliver_service_list(goodsDeliverService);
        int total = goodsDeliverServiceMapper.get_goods_deliver_service_count(goodsDeliverService);
        QueryParams pageList = new QueryParams();
        pageList.setTotal(total);
        pageList.setPage(goodsDeliverService.getPage());
        pageList.setPage_size(goodsDeliverService.getPage_size());
        pageList.setList(goodsDeliverServices);
        return success(pageList);
    }

    /**
     * 新增商品发货服务
     */
    @Transactional
    public ResData add_goods_deliver_service(GoodsDeliverService goodsDeliverService){
        int result =goodsDeliverServiceMapper.add_goods_deliver_service(goodsDeliverService);
        if(result == 1){
            return success(null);
        }
        return failed(ErrorCode.SYS_GOOdSDELIVERSERVICE_ADD_ERROR.getCode(),ErrorCode.SYS_GOOdSDELIVERSERVICE_ADD_ERROR.getMsg(),null);
    }

    /**
     * 修改商品发货服务
     */
    @Transactional
    public ResData update_goods_deliver_service(GoodsDeliverService goodsDeliverService){
        int result = goodsDeliverServiceMapper.update_goods_deliver_service(goodsDeliverService);
        if(result == 1){
            String redis_key = "GOODS_DELIVER_SERVICE"+goodsDeliverService.getId();
            logger.info("update redis...");
            redisService.set(redis_key,goodsDeliverService);  //更新缓存内容
            return success(null);
        }
        return failed(ErrorCode.SYS_GOOdSDELIVERSERVICE_UPDATE_ERROR.getCode(),ErrorCode.SYS_GOOdSDELIVERSERVICE_UPDATE_ERROR.getMsg(),null);
    }

    /**
     * 删除商品发货服务
     */
    @Transactional
    public ResData delete_goods_deliver_service(GoodsDeliverService goodsDeliverService){
        int result =goodsDeliverServiceMapper.delete_goods_deliver_service(goodsDeliverService.getId());
        if(result == 1){
            String redis_key = "GOODS_DELIVER_SERVICE"+goodsDeliverService.getId();
            logger.info("remove redis...");
            redisService.remove(redis_key);  //删除缓存
            return success(null);
        }
        return failed(ErrorCode.SYS_OBJECT_NOT_FOUND.getCode(),ErrorCode.SYS_OBJECT_NOT_FOUND.getMsg(),null);
    }

    /**
     * 充值、商品的发货流程  RECHARGE
     * changeflag 是否转换货币类型true不转换false转换
     */
    @Transactional
    public void  push_goods_recharge(OrderBean bean,boolean changeflag){
        if(!"PAIED".equals(bean.getStatus())){
            //订单状态异常，不予发货
            Log.d("订单状态异常，不予发货");
            return ;
        }
        //创建加款的交易明细记录    付款人为0，表示系统
        FinanceTradeDetail ftd = financeTradeDetailService.add_finance_trade_details(bean.getId(),bean.getCurrency_code(),"TRADE",bean.getAccount_code(),0,bean.getSeller_user_id(),bean.getTotal_amount(),bean.getTitle());
        ftd.setFinished_amount(bean.getTotal_amount());
        ftd.setStatus(Constant.FINANCE_STATUS_FINISHED);
        //获取商品的创建订单后的有效时间
        Calendar c = Calendar.getInstance();
        c.setTime(ftd.getCreate_time());
        GoodsInfo gInfo = goodsInfoService.select_goods_info_on_usefull(bean.getGoods_id());
        GoodsCategory goodsCategory = goodsCategoryMapper.select_goods_category(gInfo.getCategory_id());
        c.add(Calendar.MINUTE,goodsCategory.getOrder_pay_expire_interval());
        ftd.setPay_expire_time(c.getTime());
        financeTradeDetailService.update_finance_trade_details(ftd);

        //创建应收应付流水//创建应收应付记录    key对应款项    jsons.getInteger(key)对应金额
        FinanceTradeReceivable ftr = financeTradeReceivableService.add_finance_trade_receivable(ftd.getId(),"RECHARGE",bean.getTotal_amount(),bean.getSeller_user_id(),0);
        ftr.setStatus(Constant.FINANCE_STATUS_FINISHED);
        financeTradeReceivableService.update_finance_trade_receivable(ftr);

        HashMap<String,Object> map = financeAccountService.update_finance_account_balance(bean,ftr,changeflag);
        if(!"SUCCESS".equals(map.get("code"))){
            //账户余额处理异常
            Log.d("账户余额处理异常");
            return ;
        }

        //已收已付
        //创建已收已付记录
        FinanceTradeReceived ftrd = financeTradeReceivedService.add_finance_trade_received(ftr.getTotal_amount(),ftd.getId(),ftr.getId(),Constant.FINANCE_STATUS_FINISHED);

        //创建已收已付款项的支付信息
        financePaymentDetailService.add_finance_payment_detail(bean.getTotal_amount(),ftrd.getId(),0,"RECHARGE","RECHARGE");

    }
}
